from logging.handlers import RotatingFileHandler
from flask import Flask,g
from flask_sqlalchemy import SQLAlchemy
from config import config_dict
from flask_wtf.csrf import CSRFProtect, generate_csrf
from flask_session import Session
from redis import StrictRedis
import logging
from ihome.utils.common import RegexConverter

db = SQLAlchemy()
redis_store = None  # type:StrictRedis


def write_log(config_class):

    # 设置日志的记录等级
    # DevelopmentConfig.LOG_LEVEL  == logging.DEBUG
    # ProductionConfig.LOG_LEVEL  == logging.ERROR
    logging.basicConfig(level=config_class.LOG_LEVEL)  # 调试debug级

    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)

    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)

    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    app = Flask(__name__)
    config_class = config_dict[config_name]

    write_log(config_class)

    app.config.from_object(config_class)

    db.init_app(app)

    global redis_store
    redis_store = StrictRedis(host=config_class.REDIS_HOST, port=config_class.REDIS_PORT, decode_responses=True)

    csrf = CSRFProtect(app)

    # 利用钩子函数在每一次请求之后设置csrf_token值到cookie中
    @app.after_request
    def set_csrf_token(response):
        """补充csrf_token的逻辑"""

        # 1.生成csrf_token随机值
        csrf_token = generate_csrf()
        # 2.获取响应对象，统一设置csrf_token值到cookie中
        response.set_cookie("csrf_token", csrf_token)
        # 3.返回响应对象
        return response

    Session(app)

    app.url_map.converters["re"] = RegexConverter

    from ihome.api_1_0.index import index_bp
    from ihome.api_1_0.passport import register_login_bp
    app.register_blueprint(index_bp)
    app.register_blueprint(register_login_bp,url_prefix='/api/v1.0')
    from ihome.api_1_0.passport import api
    app.register_blueprint(api)

    from ihome.web_html import html
    app.register_blueprint(html)

    return app